package zsd.reiview.experiment.crf;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;


import org.apache.log4j.Logger;
import org.omg.CORBA.PUBLIC_MEMBER;


import zsd.reiview.utility.Utility;

import com.aliasi.dict.DictionaryEntry;
import com.aliasi.dict.MapDictionary;
import com.aliasi.dict.TrieDictionary;
import com.aliasi.util.AbstractExternalizable;
import com.aliasi.util.Compilable;
import com.aliasi.util.Files;
import com.aliasi.util.ObjectToDoubleMap;
import com.aliasi.util.ObjectToSet;
import com.aliasi.util.Streams;

/**
 * @Title: SentiDictionay.java
 * @Package zsd.reiview.coae.crf
 * @Description: TODO(添加描述)
 * @author 朱圣代
 * @date 2011-10-8 下午09:09:52
 * @version V1.0
 */
public class SentiDictionay extends MapDictionary<String> implements Compilable, Serializable {

	private static final Logger log = Logger.getLogger(SentiDictionay.class);

	public final static int BAD = -1;
	public final static int GOOD = -1;
	public final static int LEVEL = 2;
	public final static int VIEW = 3;
	public final static int ELSE = 3;
	
	public final static String GOODTAG = "G";
	public final static String BADTAG = "B";
	
	public final static File INSTANCE = new File("myDataBase" + File.separator + "SentiDic" +File.separator+"senti.dictionay");
	MapDictionary<String> catMap;
	MapDictionary<String> sortMap;
	Map map ;

	public void initFromFiles(String dir) throws Exception {

		catMap = new MapDictionary<String>();
		sortMap = new MapDictionary<String>();
		map = new HashMap<String, String >( );
		File dirFile = new File(dir);
		if (!dirFile.isDirectory())
			return;
		File[] files = dirFile.listFiles();
		for (int i = 0; i < files.length; i++) {
			String str = Files.readFromFile(files[i], "gbk");
			String[] lines = str.split("\r\n");
			if (lines.length < 10)
				lines = str.split("\n");
			String start = "";
			if (lines[0].length() >= 6)
				start = lines[0].substring(0, 6);

			for (int k = 0; k < lines.length; k++) {

				if (lines[k] == null || lines[k].length() == 0 || lines[k].length() >= 6)
					continue;
				DictionaryEntry<String> dictionaryEntry = null;
				DictionaryEntry<String> catdictionaryEntry = null;
				DictionaryEntry<String> sortdictionaryEntry = null;
				if (start.equals("中文消极评价") || start.equals("中文负面情感")) {
					dictionaryEntry = new DictionaryEntry<String>(lines[k], "B", -1);
					map.put(lines[k],"B");
					catdictionaryEntry = new DictionaryEntry<String>("B", lines[k], -1);
					sortdictionaryEntry = new DictionaryEntry<String>("-1", lines[k], -1);
				} else if (start.equals("中文积极评价") || start.equals("中文正面情感")) {
					dictionaryEntry = new DictionaryEntry<String>(lines[k], "G", 1);
					map.put(lines[k],"G");
					catdictionaryEntry = new DictionaryEntry<String>("G", lines[k], 1);
					sortdictionaryEntry = new DictionaryEntry<String>("1", lines[k], 1);
				} else if (start.equals("中文程度副词")) {
					dictionaryEntry = new DictionaryEntry<String>(lines[k], "L", 2);
					map.put(lines[k],"L");
					catdictionaryEntry = new DictionaryEntry<String>("L", lines[k], 2);
					sortdictionaryEntry = new DictionaryEntry<String>("2", lines[k], 2);
				} else if (start.equals("中文主张词语")) {
					dictionaryEntry = new DictionaryEntry<String>(lines[k], "V", 3);
					map.put(lines[k],"V");
					catdictionaryEntry = new DictionaryEntry<String>("V", lines[k], 3);
					sortdictionaryEntry = new DictionaryEntry<String>("3", lines[k], 3);
				} else if (files[i].getName().indexOf("tsinghua.negative.gb") != -1) {
					dictionaryEntry = new DictionaryEntry<String>(lines[k], "B", -1);
					map.put(lines[k],"B");
					catdictionaryEntry = new DictionaryEntry<String>("B", lines[k], -1);
					sortdictionaryEntry = new DictionaryEntry<String>("-1", lines[k], -1);
				} else if (files[i].getName().indexOf("tsinghua.positive.gb") != -1) {
					dictionaryEntry = new DictionaryEntry<String>(lines[k], "G", 1);
					map.put(lines[k],"G");
					catdictionaryEntry = new DictionaryEntry<String>("G", lines[k], 1);
					sortdictionaryEntry = new DictionaryEntry<String>("1", lines[k], 1);
				} else {
					continue;
				}
				if (phraseEntryList(lines[k]).isEmpty())
					addEntry(dictionaryEntry);
				catMap.addEntry(catdictionaryEntry);
				sortMap.addEntry(sortdictionaryEntry);
			}
		}
		// File file = new File ( INSTANCE);
	//AbstractExternalizable.compileTo( this, INSTANCE);
	 //AbstractExternalizable a=	 (AbstractExternalizable) AbstractExternalizable.readObject(INSTANCE);
	// SentiDictionay sentiDictionay =(SentiDictionay) a.readResolve();
		saveDic();
	}

	/*
	 * public void addLog() { log.error("正面情感词个数    =  " +
	 * sortMap.phraseEntryList("1").size()); log.error("负面情感词个数    =  " +
	 * sortMap.phraseEntryList("-1").size()); log.error("程度副词个数         =  " +
	 * sortMap.phraseEntryList("2").size()); log.error("主张词语个数         =  " +
	 * sortMap.phraseEntryList("3").size()); }
	 */

	public void addLog() {
		log.error("正面情感词个数    =  " + categoryEntryList("G").size());
		//log.error("正面情感词个数    =  " +map.toString());
	//	map.toString();
		log.error("负面情感词个数    =  " + categoryEntryList("B").size());
		log.error("程度副词个数         =  " + categoryEntryList("L").size());
		log.error("主张词语个数         =  " + categoryEntryList("V").size());
	}

	public String findPhraseCat(String phrase) {
		List<DictionaryEntry<String>> list = phraseEntryList(phrase);
		return list.size() == 0 ? "E" : list.get(0).category();
	}

	
	public void saveDic() throws Exception{
		FileOutputStream fileOut = null;
    BufferedOutputStream bufOut = null;
    ObjectOutputStream objOut = null;
    try {
        fileOut = new FileOutputStream(INSTANCE);
        bufOut = new BufferedOutputStream(fileOut);
        objOut = new ObjectOutputStream(bufOut);
        //compileTo(objOut);
        objOut.writeInt( size());
        for (DictionaryEntry<String> entry : entryList()) {
            entry.compileTo(objOut);
        }
    } finally {
        Streams.closeQuietly(objOut);
        Streams.closeQuietly(bufOut);
        Streams.closeQuietly(fileOut);
    }
	}
	public static SentiDictionay getInstance() throws ClassNotFoundException, IOException {
		//return (SentiDictionay) AbstractExternalizable.readObject(INSTANCE);
		//return  (SentiDictionay) AbstractExternalizable.readResourceObject(SentiDictionay.class,"G:\\1\\senti.dictionay");
		FileInputStream fileIn = null;
		BufferedInputStream bufIn = null;
		ObjectInputStream in = null;

		fileIn = new FileInputStream(INSTANCE);
		bufIn = new BufferedInputStream(fileIn);
		in = new ObjectInputStream(bufIn);
		// return objIn.readObject();

		//ObjectInput in = null;
		SentiDictionay dict = new SentiDictionay();
		int numEntries = in.readInt();
		for (int i = 0; i < numEntries; ++i) {
			// required for readObject; safe if safe write
			@SuppressWarnings("unchecked")
			DictionaryEntry<String> entry = (DictionaryEntry<String>) in.readObject();
			dict.addEntry(entry);
		}

		Streams.closeQuietly(in);
		Streams.closeQuietly(bufIn);
		Streams.closeQuietly(fileIn);

		return  dict;
	}

	public static TrieDictionary<String>getTrieDicInstance(){
		TrieDictionary<String> trieDictionary= new TrieDictionary<String>();
		try {
			SentiDictionay hashDictionay = getInstance();
			Iterator<DictionaryEntry<String>> ite = hashDictionay.iterator();
			while( ite.hasNext() )
				trieDictionary.add( ite.next());
		} catch (ClassNotFoundException e) {
			   e.printStackTrace();  
			    
		} catch (IOException e) {
			   e.printStackTrace();  
			    
		} 
		return trieDictionary;
		
	}
	
	public static void main(String[] args) throws Exception {
		SentiDictionay sentiDictionay = new SentiDictionay();
		sentiDictionay.initFromFiles("myDataBse" + File.separator + "sentiwords");
		sentiDictionay =  SentiDictionay.getInstance();
		//SentiDictionay sentiDictionay = new SentiDictionay();

		sentiDictionay.addLog();
	}
}
